package com.situ.supermarket.dao;


import com.situ.supermarket.entity.User;
import com.situ.supermarket.util.DBUtil;
import com.situ.supermarket.util.StringUtil;

import java.util.List;

public class UserDao {
    public List<User> select(Integer page, Integer limit, String username, String name) {
        String sql="select * from user where status<>-1";
        if(StringUtil.isNotBlank(username) && StringUtil.isNotBlank(name)){
            sql+=" and instr(username,?)>0 and instr(name,?)>0";
            sql+=" limit ?,?";
            return DBUtil.executeDQL(sql,User.class,username,name,(page-1)*limit,limit);
        }
        if(StringUtil.isNotBlank(name)){
            sql+=" and instr(name,?)>0 limit ?,?";
            return DBUtil.executeDQL(sql,User.class,name,(page-1)*limit,limit);
        }
        if(StringUtil.isNotBlank(username)){
            sql+=" and instr(username,?)>0 limit ?,?";
            return DBUtil.executeDQL(sql,User.class,username,(page-1)*limit,limit);
        }
        sql+=" limit ?,? ";
        return DBUtil.executeDQL(sql,User.class,(page-1)*limit,limit);
    }

    public void insert(User u) {
        String sql = "insert into user(username,password,name,tel,create_time) values(?,?,?,?,?)";
        DBUtil.executeDML(sql,u.getUsername(),u.getPassword(),u.getName(),u.getTel(),u.getCreateTime());

    }

    public void delete(Integer id) {
        String sql = "update user set status = -1 where id=?";
        DBUtil.executeDML(sql,id);
    }

    public List<User> selectById(Integer id) {
        String sql = "select * from user where id = ?";
        return DBUtil.executeDQL(sql,User.class,id);
    }

    public void update(User u) {
        String sql = "update user set username=?,password=?,name=?,tel=? where id=?";
        DBUtil.executeDML(sql,u.getUsername(),u.getPassword(),u.getName(),u.getTel(),u.getId());
    }

    public Long count(String username, String name) {
        String sql = " select count(1) from user ";
        if (StringUtil.isNotBlank(username) && StringUtil.isNotBlank(name)) {
            sql += "  where instr(username,?)>0 and instr(name,?)>0";
            return DBUtil.executeCount(sql, username, name);
        }
        if (StringUtil.isNotBlank(name)) {
            sql += "  where instr(name,?)>0";
            return DBUtil.executeCount(sql, name);
        }
        if (StringUtil.isNotBlank(username)) {
            sql += "  where instr(username,?)>0";
            return DBUtil.executeCount(sql, username);
        }
        return DBUtil.executeCount(sql);
    }

    public List<User> selectByUsername(String username) {
        String sql = "select * from user where username = ?";
        return DBUtil.executeDQL(sql,User.class,username);
    }

    public void UpdatePassword(String newPassword, Integer id) {
        String sql = "update user set password=? where id=?";
        DBUtil.executeDML(sql,newPassword,id);
    }
}

